#include "mac_additem.h"
#include "ui_mac_additem.h"

Mac_AddItem::Mac_AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Mac_AddItem)
{
    ui->setupUi(this);

    table=TD_MAC_ADDR;

    updateDepartments();
    ui->devices->addItems(devices);
}

Mac_AddItem::~Mac_AddItem()
{
    delete ui;
}

void Mac_AddItem::updateDepartments()
{
    if(ui->departments->count() != 0)
        ui->departments->clear();

    auto items=sp_getCategory("department",table);
    if(items.isEmpty())
        ui->departments->addItems(parts);
    else
        ui->departments->addItems(items);
    ui->departments->setCurrentIndex(-1);
}

bool Mac_AddItem::addItem(const QString &department,
                          const QString &name,
                          const QString &device,
                          const QString &mac_addr)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (department,name,device,mac) values (?,?,?,?)")
                  .arg(table));
    query.addBindValue(department);
    query.addBindValue(name);
    query.addBindValue(device);
    query.addBindValue(mac_addr);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void Mac_AddItem::on_btn_submit_clicked()
{
    QString department=ui->departments->currentText();
    QString name=ui->name->text().trimmed();
    QString device=ui->devices->currentText();
    QString mac=ui->mac_addr->text().trimmed();

    if(name.isEmpty() || mac.isEmpty())
        return;

    if(mac.contains(":"))
        mac=mac.replace(":","-");

    if(addItem(department,name,device,mac))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT;
}

void Mac_AddItem::on_btn_paste_clicked()
{
    QString mac=qApp->clipboard()->text();
    if(!mac.isEmpty())
    {
        if(mac.contains(":"))
            mac=mac.replace(":","-");
        ui->mac_addr->setText(mac);
    }
}

void Mac_AddItem::on_btn_parse_clicked()
{
    QString name=ui->name->text().trimmed();
    if(name.contains("-"))
    {
        auto pair=name.split("-");
        auto department=pair.first();
        if(parts.contains(department))
            ui->departments->setCurrentText(department);
        name=pair.last();
        ui->name->setText(name);
    }
}
